package cn.sunxyz.core.bean;

import cn.sunxyz.core.bean.plugin.Plugin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.annotation.Annotation;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by yangrd on 2017/5/20.
 */
public class BeanContextHelper {

    private static final Logger logger = LoggerFactory.getLogger(BeanContextHelper.class);

    private static ClassContainer classContainer;
    private static List<Plugin> pluginList;

    /**
     * 初始化bean的上下文
     */
    public static void initBeanContext(Collection<Class<?>> classCollection) {
        classContainer = new DefaultClassContainer(classCollection);//获取所有bean
        BeanContext.initBean(classContainer);
        pluginList = PluginsManger.initPlugins(classContainer);
        runPlugins();
    }

    private static void runPlugins() {
        pluginList.forEach(plugin -> {
            logger.debug("[init plugin] :=> {}", plugin);
            plugin.before(classContainer::listClassByAnnotation);
            BeanContext.getBeanMap().forEach((cls, obj) ->
                    BeanContext.putBean(cls, plugin.createTarget(cls, obj))
            );
            plugin.after(BeanContextHelper::mapByAnnotation);
        });
    }

    /**
     * 获取指定父类或接口的相关类
     */
    public static List<Class<?>> listClassBySuper(Class<?> superClass) {
        return classContainer.listClassBySuper(superClass);
    }

    private static Map<Class<?>, Object> mapByAnnotation(Class<? extends Annotation> annotationClass) {
        return classContainer.listClassByAnnotation(annotationClass).stream().map(BeanContext::getBean).collect(Collectors.toMap(Object::getClass, obj -> obj));
    }

}
